package Q744

class Main {

}

fun main() {
    var char : CharArray = charArrayOf('c','f','j')
    val target : Char  = 'j'
    var nextGreatestLetter = Solution().nextGreatestLetter(char, target)
    print(nextGreatestLetter)
}

class Solution {
    fun nextGreatestLetter(letters: CharArray, target: Char): Char {
        val len = letters.size
        if (target >= letters[len - 1]) {
            return letters[0]
        }
        var low = 0
        var height = len - 1
        while (low <= height) {
            val mid = (low + height) ushr 1
            when {
                letters[mid] > target -> height = mid - 1
                else -> low = mid + 1
            }
        }
        return letters[low]
    }
}